package com.zbkj.service.service.mszs;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.qcloud.cos.utils.Md5Utils;
import com.qiniu.util.StringUtils;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.constants.NotifyConstants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.mszs.MszsHotel;
import com.zbkj.common.model.mszs.MszsOrder;
import com.zbkj.common.model.mszs.MszsQimoReceivekey;
import com.zbkj.common.model.mszs.MszsRoom;
import com.zbkj.common.model.sms.SmsTemplate;
import com.zbkj.common.model.system.SystemNotification;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.service.service.sms.SmsService;
import com.zbkj.service.service.sms.SmsTemplateService;
import com.zbkj.service.service.config.SystemConfigService;
import com.zbkj.service.service.config.SystemNotificationService;
import com.zbkj.service.service.mszs.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @description 民宿助手订单表-service接口
 * @author lingfe
 * @date 2023-11-16
 */
@Slf4j
@Service
public class QimoWebCallServiceImpl implements QimoWebCallService {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SystemNotificationService systemNotificationService;

    @Lazy
    @Autowired
    private SmsService smsService;

    @Lazy
    @Autowired
    private SmsTemplateService smsTemplateService;

    @Autowired
    private MszsOrderService mszsOrderService;

    @Autowired
    private MszsQimoReceivekeyService mszsQimoReceivekeyService;

    @Autowired
    private MszsRoomService mszsRoomService;

    @Autowired
    private MszsHotelService mszsHotelService;

    @Override
    public void chuliQimoYiwuData(String key, String phone,String order6) {
        //验证按键
        boolean keyBl = "1、2".contains(key);
        if(!keyBl){
            throw new CrmebException("按键错误！");
        }

        //根据后6位订单号-得到订单
        MszsOrder mszsOrder = mszsOrderService.getWhereOrder6One(order6);
        if (mszsOrder == null) {
            throw new CrmebException("没有找到订单！");
        }else{
            mszsOrder.setUserPhone(phone);
            mszsOrderService.updateById(mszsOrder);
        }

        //酒店信息，发送酒店信息短信
        if("1".equals(key)){
            MszsHotel mszsHotel = mszsHotelService.getById(mszsOrder.getJdId());
            sendHotelInfoSms(phone,mszsHotel);
            return;
        }

        //得到关联的房间信息
        MszsRoom mszsRoom = mszsRoomService.getById(mszsOrder.getRoomId());
        if (!sendRoomInfoSms(phone, mszsRoom)) {
            throw new CrmebException("发送失败！");
        }

        //得到通知模板设置
        SystemNotification payNotification = systemNotificationService.getByMark(NotifyConstants.HOTEL_ROOM_INFO);
        //发送短信-验证通知模板设置
        if (StrUtil.isNotBlank(phone) && payNotification.getIsSms().equals(1)) {
            //获取短信模板
            SmsTemplate smsTemplate = smsTemplateService.getDetail(payNotification.getSmsId());
            //记录按键信息
            MszsQimoReceivekey qimoReceivekey = new MszsQimoReceivekey();
            qimoReceivekey.setPhone(phone);
            qimoReceivekey.setKeyInfo(key);
            qimoReceivekey.setIsSms(Boolean.TRUE);
            qimoReceivekey.setSmsTemplateId(smsTemplate.getTempId());
            qimoReceivekey.setSmsContent(smsTemplate.getContent());
            mszsQimoReceivekeyService.save(qimoReceivekey);
        }
    }

    private Boolean sendHotelInfoSms(String phone, MszsHotel mszsHotel) {
        if(mszsHotel == null){
            throw new CrmebException("订单没有绑定酒店或酒店信息已不存在！");
        }

        //设置参数
        String hotel = mszsHotel.getJdName();
        String address =  mszsHotel.getJdAddress();
        String hotelPhone = mszsHotel.getJdPhone();

        //得到通知模板设置
        SystemNotification payNotification = systemNotificationService.getByMark(NotifyConstants.HOTEL_INFO);
        //发送短信-验证通知模板设置
        if (StrUtil.isNotBlank(phone) && payNotification.getIsSms().equals(1)) {
            SmsTemplate smsTemplate = smsTemplateService.getDetail(payNotification.getSmsId());
            return smsService.sendHotelInfo(phone, hotel, address, hotelPhone, Integer.valueOf(smsTemplate.getTempId()));
        }else{
            return Boolean.FALSE;
        }
    }

    public Boolean sendRoomInfoSms(String phone, MszsRoom mszsRoom) {
        if(mszsRoom == null){
            throw new CrmebException("没有找到房间信息");
        }
        StringBuffer roomStringBuffer = new StringBuffer();
        roomStringBuffer.append(mszsRoom.getFjFloor()).append(mszsRoom.getFjNumber());//"16楼1605";//房号
        String room = roomStringBuffer.toString();
        StringBuffer wifiStringBuffer=new StringBuffer();
        wifiStringBuffer.append(mszsRoom.getFjWifiName()).append("/").append(mszsRoom.getFjWifiPwd());//"wifi名称/wifi密码"; //wifi信息
        String wifi = wifiStringBuffer.toString();
        String fangjingPwd = mszsRoom.getFjPwd();//"160555";    //房间密码

        //得到通知模板设置
        SystemNotification payNotification = systemNotificationService.getByMark(NotifyConstants.HOTEL_ROOM_INFO);
        //发送短信-验证通知模板设置
        if (StrUtil.isNotBlank(phone) && payNotification.getIsSms().equals(1)) {
            SmsTemplate smsTemplate = smsTemplateService.getDetail(payNotification.getSmsId());
            return smsService.sendHotelRoomInfo(phone, room, fangjingPwd, wifi, Integer.valueOf(smsTemplate.getTempId()));
        }else{
            return Boolean.FALSE;
        }
    }

    /**
     * 七陌拨号请求设置-使用测试默认设置
     * -内部测试调用
     */
    public void qimoCallRequestSetTestDefault(){
        //获取七陌配置
        HashMap<String, String> configQimo = systemConfigService.info(Constants.CONFIG_FORM_ID_QIMO);
        //是否开启
        String isAutoCall = configQimo.get("isAutoCall");
        //验证是否开启
        if("false".equals(isAutoCall)){
            throw new CrmebException("未开启！");
        }

        //账户编号：https://developer.7moor.com/dc/#/other/data
        String account =configQimo.get("qimo_account");
        //账号接口密钥、令牌
        String qimoApiSecret=configQimo.get("qimoApiSecret");
        //url
        String qimoWebCallUrl = configQimo.get("qimoWebCallUrl");
        //虚拟服务号
        String qimoServiceNo = configQimo.get("qimoServiceNo");
        //测试号码
        String qimoTestPhone = configQimo.get("qimoTestPhone");
        //酒店名称(测试配置)
        String qimoJdName = "贵阳熙喆酒店民宿";

        //向七陌-发起拨号请求
        requestPostQimoWebCall(account, qimoApiSecret, qimoWebCallUrl, qimoServiceNo, qimoTestPhone, qimoJdName);
    }

    /**
     * 七陌拨号请求设置
     * @param phone     被呼手机号
     * @param jdName    酒店名称
     */
    public void qimoCallRequestSet(String phone, String jdName){
        //获取七陌配置
        HashMap<String, String> configQimo = systemConfigService.info(Constants.CONFIG_FORM_ID_QIMO);
        //是否开启
        String isAutoCall = configQimo.get("isAutoCall");
        //验证是否开启
        if("false".equals(isAutoCall)){
            log.info("isAutoCall:{},未开启！",isAutoCall);
            throw new CrmebException("未开启！");
        }
        //验证手机号
        if(StringUtils.isNullOrEmpty(phone)){
            log.info("phone:{},手机号为空！",phone);
            throw new CrmebException("手机号为空！");
        }

        //账户编号：https://developer.7moor.com/dc/#/other/data
        String account =configQimo.get("qimo_account");
        //账号接口密钥、令牌
        String qimoApiSecret=configQimo.get("qimoApiSecret");
        //url
        String qimoWebCallUrl = configQimo.get("qimoWebCallUrl");
        //虚拟服务号
        String qimoServiceNo = configQimo.get("qimoServiceNo");

        //向七陌-发起拨号请求
        requestPostQimoWebCall(account, qimoApiSecret, qimoWebCallUrl, qimoServiceNo, phone, jdName);
    }

    /**
     * 向七陌-发起拨号请求
     * @param account           七陌账户编号
     * @param qimoApiSecret     七陌账户密钥
     * @param qimoWebCallUrl    url请求地址
     * @param qimoServiceNo     虚拟服务号
     * @param phone             被呼手机号
     * @param jdName            酒店名称
     */
    private String requestPostQimoWebCall(String account, String qimoApiSecret, String qimoWebCallUrl, String qimoServiceNo, String phone, String jdName) {
        try {
            //时间戳
            String datetimeStr = DateUtil.nowDate("yyyyMMddHHmmss");

            //拼接url
            String sig = generateSig(account, qimoApiSecret, datetimeStr);
            StringBuffer url = new StringBuffer();
            url.append(qimoWebCallUrl).append(account).append("?sig=").append(sig);
            log.info("url:{}",url);

            //设置post请求
            HttpPost post = new HttpPost(url.toString());
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            String strAuthorization = generateAuthorization(account, datetimeStr);
            post.addHeader("Authorization", strAuthorization);
            post.setEntity(this.setQimoWebCallParam(qimoServiceNo, phone, jdName));

            //创建http请求
            //向七陌-发送拨打请求
            HttpClientBuilder builder = HttpClientBuilder.create();
            CloseableHttpClient client = builder.build();
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "utf8");
            log.info("the response is : {}" , responseString);
            //释放资源
            client.close();
            response.close();
            return responseString;
        } catch (Exception var20) {
            var20.printStackTrace();
            throw new CrmebException(var20.getMessage());
        }
    }

    /**
     * 生成请求头action
     * @param account 七陌账户编号
     * @param datetimeStr 时间戳
     * @return String
     */
    private static String generateAuthorization(String account, String datetimeStr) {
        return Base64.encode(account + ":" + datetimeStr,"utf-8");
    }

    /**
     * 生成签名-sig
     * @param account     七陌账户编号
     * @param qimoApiSecret 七陌账户密钥
     * @param datetimeStr   时间戳
     * @return String
     */
    private static String generateSig(String account, String qimoApiSecret, String datetimeStr) {
        //生成签名-sig
        String sig = Md5Utils.md5Hex(account + qimoApiSecret + datetimeStr);
        return sig.toUpperCase();
    }

    /**
     * 设置七陌-webcall请求参数
     * @param qimoServiceNo 虚拟服务号
     * @param phon 被呼手机号
     * @param jdName 酒店名称
     * @return StringEntity
     */
    private StringEntity setQimoWebCallParam(String qimoServiceNo, String phon, String jdName) {
        //设置参数
        Map<String,Object> mapParam=new HashMap<>();
        //固定值
        mapParam.put("Action","Webcall");
        //虚拟服务号
        mapParam.put("ServiceNo", qimoServiceNo);
        //被呼手机号
        mapParam.put("Exten",phon);
        //接听语音
        mapParam.put("Variable","name:"+ jdName);
        //mapParam.put("Variable","text:\"你好，我们是熙喆酒店民宿，欢迎您的入住！\"");
        //转为json
        String paramJson = JSON.toJSONString(mapParam);
        log.info("paramJson:{}",paramJson);
        //转为StringEntity
        StringEntity requestEntity = new StringEntity(paramJson,"utf-8");
        log.info("requestEntity:{}",requestEntity);
        return requestEntity;
    }

}
